package com.dotflat.physicalevaluate.service.impl;


import com.dotflat.physicalevaluate.domain.pe.Dimension;
import com.dotflat.physicalevaluate.domain.pe.Measure;
import com.dotflat.physicalevaluate.repository.DimensionRepository;
import com.dotflat.physicalevaluate.repository.ImportRecordRepository;
import com.dotflat.physicalevaluate.repository.MeasureRepository;
import com.dotflat.physicalevaluate.service.ImportService;
import com.matt.commons.exception.BusinessException;
import com.matt.commons.model.ErrorCode;
import com.matt.foundation.model.MemVerificationCache;
import com.matt.service.ChildrenService;
import com.matt.service.ClassesService;
import com.matt.service.UploadService;
import com.tuo51.foudation.constant.CommonConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashSet;

@Service
@Slf4j
public class ImportServiceImpl implements ImportService {

    @Autowired
    private MemVerificationCache cache;

//    @Autowired
//    private StaffService staffService;

    @Autowired
    private ChildrenService childrenService;

    @Autowired
    private ClassesService classesService;

    @Autowired
    private DimensionRepository dimensionRepository;

    @Autowired
    private ImportRecordRepository importRecordRepository;

    @Autowired
    private MeasureRepository measureRepository;

    @Autowired
    UploadService uploadService;

    class HighLowValue {
        public int high;
        public int low;
    }

    public HighLowValue highLowOf(String valStr){
        String comps[] = valStr.split("-");
        if (comps.length != 2){
            throw new BusinessException(ErrorCode.DATE_FORMAT_ERROR, "格式化错误");
        }

        float a = Float.parseFloat(comps[0]);
        float b = Float.parseFloat(comps[1]);

        HighLowValue ret = new HighLowValue();
        if (a < b){
            ret.low = (int)(a * 10);
            ret.high = (int)(b * 10);
        }else {
            ret.low = (int)(b * 10);
            ret.high = (int)(a * 10);
        }
        return ret;
    }

    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Boolean importEvaluateMeasure(MultipartFile file){
        if (file==null) {
            throw  new BusinessException("12345", "file 不能为空");
        }


        //
        try {
            XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());

            //仅使用第一个sheet
            XSSFSheet sheet = workbook.getSheetAt(0);



            //获取多少行
            int rows = sheet.getPhysicalNumberOfRows();

            if (rows <= 0){
                return true;
            }

            //
            HashSet <Measure> cache = new HashSet<>();

            //遍历每一行，注意：第 0 行为标题
            for (int j = 1; j < rows; j++) {
                //获得第 j 行
                XSSFRow row = sheet.getRow(j);

                //项目	性别	单位	限定条件	1分	2分	3分	4分	5分
                String project = row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                String gender = row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                String unit = row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                String limit = row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                String score1 = row.getCell(4, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                String score2 = row.getCell(5, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                String score3 = row.getCell(6, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                String score4 = row.getCell(7, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                String score5 = row.getCell(8, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();

                if (StringUtils.isAnyEmpty(project, gender, unit, limit, score1, score2, score3, score4, score5)){
                    throw new BusinessException(ErrorCode.JSON_STR_ERROR, "参数错误");
                }

                HighLowValue l1 = highLowOf(limit);
                HighLowValue v1 = highLowOf(score1);
                HighLowValue v2 = highLowOf(score2);
                HighLowValue v3 = highLowOf(score3);
                HighLowValue v4 = highLowOf(score4);
                HighLowValue v5 = highLowOf(score5);

                CommonConstant.Gender g = CommonConstant.Gender.get(gender);

                Dimension dimension = dimensionRepository.getTop1ByProject(project);
                if (dimension == null){
                    dimension = dimensionRepository.getTop1ByName(project);
                }
                if (dimension == null){
                    throw new BusinessException(ErrorCode.JSON_STR_ERROR, "找不到维度");
                }
                //
                Measure m1 = Measure.of(dimension.getId(), g.codeOf(), l1.low, l1.high, unit, v1.low, v1.high, "需努力", 1);
                Measure m2 = Measure.of(dimension.getId(), g.codeOf(), l1.low, l1.high, unit, v2.low, v2.high, "正常", 2);
                Measure m3 = Measure.of(dimension.getId(), g.codeOf(), l1.low, l1.high, unit, v3.low, v3.high, "良好", 3);
                Measure m4 = Measure.of(dimension.getId(), g.codeOf(), l1.low, l1.high, unit, v4.low, v4.high, "优秀", 4);
                Measure m5 = Measure.of(dimension.getId(), g.codeOf(), l1.low, l1.high, unit, v5.low, v5.high, "超常", 5);

                cache.add(m1);
                cache.add(m2);
                cache.add(m3);
                cache.add(m4);
                cache.add(m5);

            }

//            保存
            measureRepository.saveAll(cache);

        } catch (IOException e) {
            throw new BusinessException("12345", "错误");
        }
        return true;
    }

    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Boolean importEvaluateDimension(MultipartFile file){
        if (file==null) {
            throw  new BusinessException("12345", "file 不能为空");
        }


        //
        try {
            XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());

            //仅使用第一个sheet
            XSSFSheet sheet = workbook.getSheetAt(0);



            //获取多少行
            int rows = sheet.getPhysicalNumberOfRows();

            if (rows <= 0){
                return true;
            }

            //
            HashSet <Dimension> cache = new HashSet<>();

            //遍历每一行，注意：第 0 行为标题
            for (int j = 1; j < rows; j++) {
                //获得第 j 行
                XSSFRow row = sheet.getRow(j);

                //测查维度	项目名	测查要求	测查方法	综合评价	概况评估	通过结论	不通过结论	提升建议
                String name = row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                String project = row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                String keyPoint = row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                String guide = row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                String composite = row.getCell(4, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                String about = row.getCell(5, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                String passResult = row.getCell(6, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                String failResult = row.getCell(7, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                String advise = row.getCell(8, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();

                if (StringUtils.isAnyEmpty(name, keyPoint, guide, passResult, failResult, advise)){
                    throw new BusinessException(ErrorCode.JSON_STR_ERROR, "参数错误");
                }

                //创建维度
                Dimension dimension = new Dimension();
                dimension.setName(StringUtils.trim(name));
                dimension.setProject(StringUtils.trim(project));
                dimension.setKeyPoint(StringUtils.trim(keyPoint));
                dimension.setGuide(StringUtils.trim(guide));
                dimension.setPassResult(StringUtils.trim(passResult));
                dimension.setFailResult(StringUtils.trim(failResult));
                dimension.setAdvise(StringUtils.trim(advise));

                cache.add(dimension);

            }

//            保存
            dimensionRepository.saveAll(cache);

        } catch (IOException e) {
            throw new BusinessException("12345", "错误");
        }
        return true;
    }

}
